package javase0829;

import java.io.*;
import java.net.DatagramSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


public class LoginClient {
    public static final String HOST = "127.0.0.1";
    public static final int PORT = 8888;

    private static String action = "login";

    private static String token;

    public static void main(String[] args) throws Exception {

        //提示信息，录入，判断（结束？继续？）
        String mes = "请输入登录信息，账号密码之间用英文逗号分隔：";
        Scanner sc = new Scanner(System.in);
        System.out.println(mes);
        do {

            String s = sc.nextLine();
            if ("quit".equals(s)) {
                System.out.println("已退出。");
                break;
            } else {
                sendAndReceive(s);
                //mes = "请输入信息：";
            }

        } while(true);

    }

    public static void sendAndReceive(String mes) {
        try {
            Socket socket = new Socket(LoginClient.HOST, LoginClient.PORT);

            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            Object out = out(mes);
           // System.out.println("bunny" + out);
            oos.writeObject(out);
            socket.shutdownOutput();

            ObjectInputStream ois = new ObjectInputStream(is);
            Object in = ois.readObject();
           // System.out.println("bunny" + in);
            print(in);

            oos.close();
            ois.close();
            os.close();
            is.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void print(Object in) {
        try {
            Map<String, String> dto = (Map<String, String>) in;
            System.out.println(dto.get("mes"));
            token = dto.get("token");
            action = dto.get("action");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static Object out(String mes) {
        //action 干什么？ mes  token身份信息
        Map<String, String> dto = new HashMap<>();
        dto.put("action", action);
        dto.put("mes",mes.trim());
        dto.put("token",token);

        return dto;
    }


}
